# 面试题59 - II. 队列的最大值
# 请定义一个队列并实现函数 max_value 得到队列里的最大值，要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。

# 若队列为空，pop_front 和 max_value 需要返回 -1

# 示例 1：

# 输入: 
# ["MaxQueue","push_back","push_back","max_value","pop_front","max_value"]
# [[],[1],[2],[],[],[]]
# 输出: [null,null,null,2,1,2]
# 示例 2：

# 输入: 
# ["MaxQueue","pop_front","max_value"]
# [[],[],[]]
# 输出: [null,-1,-1]

from queue import Queue, deque
class MaxQueue:
    
    def __init__(self):
        self.queue = Queue()
        self.deque = deque()

    def max_value(self) -> int:
        """取最大值"""
        return self.deque[0] if self.deque else -1

    def push_back(self, value: int) -> None:
        """将元素放入双端队列，如果值比之前的某一个元素大，把那个元素后面的都删除，再把元素放在那个元素后面
        """
        self.queue.put(value)
        while self.deque and self.deque[-1] < value:
            self.deque.pop()
        self.deque.append(value)


    def pop_front(self) -> int:
        value = -1 if self.queue.empty() else self.queue.get()
        if self.deque and  value == self.deque[0]:
            self.deque.popleft()
        return value

def test():
    max_queue = MaxQueue()
    max_queue.push_back(7)
    assert max_queue.max_value() == 7
    max_queue.push_back(2)
    max_queue.push_back(5)
    max_queue.push_back(11)
    assert max_queue.max_value() == 11
    max_queue.push_back(6)
    assert max_queue.max_value() == 11
    assert max_queue.pop_front() == 7
    assert max_queue.pop_front() == 2
    assert max_queue.pop_front() == 5
    assert max_queue.pop_front() == 11
    assert max_queue.max_value() == 6
    assert max_queue.pop_front() == 6
    assert max_queue.max_value() == -1
    assert max_queue.pop_front() == -1